/*
 Copyright (c) 2009 Rafal Szemraj - http://szemraj.eu

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all 
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/
package eu.szemraj.utils {
    import eu.szemraj.utils.platform.PlayerType;   
    import eu.szemraj.utils.platform.PlatformUtil;   

    public class StringUtil {

        private static const firstCharRegExp:RegExp = new RegExp( "^(.)", "" );
		
		
        public static function isEmpty( str:String ):Boolean {
   		
   			return !(str != null && str != "" && str.toLocaleLowerCase() != "null" && str.toLocaleLowerCase() != "undefined");
        }

		/**
		 * Adds chars chars before string to provide given string length
		 * @param string input string
		 * @param totalLength length of string after operation
		 * @param char char to use as extension ( default is zero )
		 * @return String extended string
		 */
        public static function addTrailingChars( string:String, totalLength:int, char:String = "0"  ):String {
   		
            if( string.length >= totalLength ) return string; else {
   			
                while( string.length < totalLength ) {
   				
                    string = char + string;		
                }	
            }
            return string;
        }

        public static function cropTo( string:String, totalLength:Number, cropMarker:String = "..." ):String {

            if( string.length <= totalLength ) return string;  		
            var stringLength:Number = totalLength - cropMarker.length;	
            return string.substr( 0, stringLength ) + cropMarker;
        }

		/**
		 * Removes html tags from string
		 * @param string input string
		 * @return String string without tags
		 */
        public static function stripTags( string:String ):String {
   	
            if ( string == null) { 
                return ''; 
            }
            return string.replace( /<\/?[^>]+>/igm, '' );    
        }

		/**
		 * Trims string ( removes all spaces in front of and at the end of string
		 * @param string input string
		 * @return String trimmed string
		 */
        public static function trim( string:String):String {
   	
            if (string == null) { 
                return ''; 
            }
            return string.replace( /^\s+|\s+$/g, '' );
        }

        public static function trimLeft(string:String):String {
   	
            if (string == null) { 
                return ''; 
            }
            return string.replace( /^\s+/, '' );
        }

        public static function trimRight(string:String):String {
   	
            if (string == null) { 
                return ''; 
            }
            return string.replace( /\s+$/, '' );
        }

        public static function countWords( string:String):uint {
            if (string == null) { 
                return 0; 
            }
            return string.match( /\b\w+\b/g ).length;
        }  

        public static function remove( string:String, stringToRemove:String, caseSensitive:Boolean = true):String {
            if (string == null) { 
                return ''; 
            }
            var rem:String = stringToRemove.replace( /(\]|\[|\{|\}|\(|\)|\*|\+|\?|\.|\\)/g, '\\$1' );
            var flags:String = (!caseSensitive) ? 'ig' : 'g';
            return string.replace( new RegExp( rem, flags ), '' );
        }   

        public static function containsChar( string:String, char:String):Boolean {
            if (string == null) { 
                return false; 
            }
            return string.indexOf( char ) != -1;
        }

        public static function breakApart( string:String, maxPartLength:uint, delimeter:String = "."):Array {
            var arr:Array = new Array( );
            if (string == null || !containsChar( string, delimeter )) { 
                return arr; 
            }
            var chrIndex:uint = 0;
            var strLen:uint = string.length;
            var replPatt:RegExp = new RegExp( "[^" + delimeter.replace( /(\]|\[|\{|\}|\(|\)|\*|\+|\?|\.|\\)/g, '\\$1' ) + "]+$", "i" );
            while (chrIndex < strLen) {
                var subString:String = string.substr( chrIndex, maxPartLength );
                if (!containsChar( subString, delimeter )) {
                    arr.push( cropTo( subString, subString.length ) );
                    chrIndex += subString.length;
                }
                subString = subString.replace( replPatt, '' );
                arr.push( subString );
                chrIndex += subString.length;
            }
            return arr;
        }         

        public static function suppressSingleLetters(str:String):String {
      	
            return str.replace( /\s+([aiouwzAIOUWZ])\s+/g, " $1&nbsp;" );
        }

        public static function replace( str:String, strToFind:String, strToReplace:String ):String {
      	
            return "" + str.split( strToFind ).join( strToReplace );
        }

        public static function createMultiLineString( str:String, maxCharsInLine:Number ):String {
        
            if( str.length < maxCharsInLine ) return str;
        	
            str = StringUtil.trim( str );
            str = StringUtil.replace( str, "      ", " " );
            str = StringUtil.replace( str, "     ", " " );
            str = StringUtil.replace( str, "    ", " " );
            str = StringUtil.replace( str, "   ", " " );
            str = StringUtil.replace( str, "  ", " " );
            
            var wordsArr:Array = str.split( " " );
            var outputStr:String = "";
            var tempString:String = "";
            var i:Number = 0;
            while( i < wordsArr.length ) {
				
                while( ( tempString + " " + String( wordsArr[i] ) ).length < maxCharsInLine && wordsArr[i] ) {
						
                    tempString += ( " " + String( wordsArr[i] ) );
                    i++;
                }			
                if( tempString == "" ) {
						
                    tempString = wordsArr[i];
                }
                outputStr += tempString.slice( 1 ) + "\n";
                tempString = "";
            }
            if( outputStr.indexOf( " " ) == 0  ) outputStr = outputStr.slice( 1 );
            return outputStr;
        }

        public static function mapPolishChars( charCode:Number ):String {
    	
            var char:String;
            if( PlatformUtil.getPlayerType( ) == PlayerType.ACTIVEX ) {
				
                switch( charCode ) {
					
                    case 5    : 
                        char = "ą"; 
                        break;
                    case 4    : 
                        char = "Ą"; 
                        break;
                    case 25   : 
                        char = "ę"; 
                        break;
                    case 24   : 
                        char = "Ę"; 
                        break;
                    case 91   : 
                        char = "ś"; 
                        break;
                    case 90   : 
                        char = "Ś"; 
                        break;
                    case 122  : 
                        char = "ź"; 
                        break;
                    case 121  : 
                        char = "Ź"; 
                        break;
                    case 124  : 
                        char = "ż"; 
                        break;
                    case 123  : 
                        char = "Ż"; 
                        break;
                    case 111  : 
                        char = "ó"; 
                        break;
                    case 79   : 
                        char = "Ó"; 
                        break;
                    case 68   : 
                        char = "ń"; 
                        break;
                    case 67   : 
                        char = "Ń"; 
                        break;
                    case 66   : 
                        char = "ł"; 
                        break;
                    case 65   : 
                        char = "Ł"; 
                        break;
                    case 7    : 
                        char = "ć"; 
                        break;
                    case 6    : 
                        char = "Ć"; 
                        break;
                    default   : 
                        return String.fromCharCode( charCode );
                }
            } else {
			
                switch( charCode ) {
			
                    case 97   : 
                        char = "ą"; 
                        break;
                    case 65   : 
                        char = "Ą"; 
                        break;
                    case 101  : 
                        char = "ę"; 
                        break;
                    case 69   : 
                        char = "Ę"; 
                        break;
                    case 115  : 
                        char = "ś"; 
                        break;
                    case 83   : 
                        char = "Ś"; 
                        break;
                    case 120  : 
                        char = "ź"; 
                        break;
                    case 88   : 
                        char = "Ź"; 
                        break;
                    case 122  : 
                        char = "ż"; 
                        break;
                    case 90   : 
                        char = "Ż"; 
                        break;
                    case 111  : 
                        char = "ó"; 
                        break;
                    case 79   : 
                        char = "Ó"; 
                        break;
                    case 110  : 
                        char = "ń"; 
                        break;
                    case 78   : 
                        char = "Ń"; 
                        break;
                    case 108  : 
                        char = "ł"; 
                        break;
                    case 76   : 
                        char = "Ł"; 
                        break;
                    case 99   : 
                        char = "ć"; 
                        break;
                    case 67   : 
                        char = "Ć"; 
                        break;
					
                    default   : 
                        char = String.fromCharCode( charCode );
                }
            }
            return char;
        }

        public static function pluralize( str:String):String {
            var lastCharIndex:uint = str.length - 1;
            var lastChar:String = str.charAt( lastCharIndex );

            return (lastChar == 'y') ? (str.substr( 0, lastCharIndex ) + 'ies') : str + ((lastChar == 's') ? 'es' : 's');
        }

        public static function upperCaseFirstChar( str:String ):String {
        	
            var result:Object = str.match( firstCharRegExp );
            return str.replace( firstCharRegExp, result[1].toUpperCase( ) );                    
        }

        public static function toString( str:String, defaultString:String = '' ):String {

            return str || defaultString;
        }
    }
}
